package cn.kinoko.interceptors;

import cn.kinoko.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 返回时间拦截器
 *
 * @author kinoko
 */
@Order(1)
@Slf4j
public class RTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        ThreadLocalUtil.put("rt", System.currentTimeMillis());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        Long startTime = (Long) ThreadLocalUtil.get("rt");
        if (startTime != null) {
            Long useTime = System.currentTimeMillis() - startTime;
            log.info("url: {} rt: {}ms", request.getRequestURL(), useTime);
            if (useTime > 1000) {
                log.warn("catch slow API url: {} rt: {}ms", request.getRequestURL(), useTime);
            }
        }
        ThreadLocalUtil.remove("rt");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
